#include "pch.h"

#include "CJobDispatcher.h"

#include "CCGenGpu.h"

CJobDispatcher::CJobDispatcher()
{
	filterGraph = nullptr;
	filterJobBufferNode = nullptr;
	matchWithLUTNode = nullptr;
	computeTapDirLUTBufferNode = nullptr;
	computeFilterExtentsLUTBufferNode = nullptr;
	vectorizeCubemapBufferNode = nullptr;
	vectorizeCubemapNode = nullptr;
	computeTapDirLUTNode = nullptr;
	computeFilterExtentsLUTNode = nullptr;
	filterLevelJobBufferNode = nullptr;
	processFilterJobNode = nullptr;
	totalJobCount = 0;
	processedJobCount = 0;
#ifdef USE_GPU
	gpuHandler = new CCGenGpu(this);
#endif

}

bool CJobDispatcher::IsGpuEnabled()
{
#ifdef USE_GPU
	return gpuHandler->IsGpuEnabled();
#else
	return false;
#endif
}

void CJobDispatcher::WaitForAll()
{
	while(totalJobCount != processedJobCount)
	{
		Sleep(1);
	}
}

CJobDispatcher::~CJobDispatcher()
{
#ifdef USE_GPU
	SAFE_DELETE(gpuHandler);
#endif

	for(unsigned int i=0; i < filterStates.size(); i++)
	{
		SAFE_DELETE(filterStates[i]);	
	}
	filterStates.clear();

	for(unsigned int i=0; i < tapdirLuts.size(); i++)
	{
		SAFE_DELETE(tapdirLuts[i]);	
	}
	tapdirLuts.clear();

	for(unsigned int i=0; i < filterExtentsLuts.size(); i++)
	{
		SAFE_DELETE(filterExtentsLuts[i]);	
	}
	filterExtentsLuts.clear();
}

void CJobDispatcher::RemoveActiveJobAndNotify( SFilterJobInternal *internalJob )
{
	if(internalJob->job.onCompleteCallback)
	{
		internalJob->job.onCompleteCallback(internalJob->job.userPtr);
	}

	int faceCount = internalJob->vectorCubemap->mipCount * 6;
	for(int i_face = 0; i_face < faceCount; i_face++)
	{
		internalJob->vectorCubemap->faces[i_face].Clear();
	}

	activeJobMutex.lock();
	auto it = std::find(activeJobList.begin(), activeJobList.end(), internalJob);

	if(it != activeJobList.end())
	{
		SAFE_DELETE(*it);
		activeJobList.erase(it);
	}

	activeJobMutex.unlock();
}

STapdirLUT::~STapdirLUT()
{
	SAFE_DELETE_ARRAY(dataPtrs);
#ifdef USE_GPU
	SAFE_DELETE(gpuDataPtrs);
#endif
}

SFilterExtentsLUT::~SFilterExtentsLUT()
{
	SAFE_DELETE_ARRAY(dataPtrs);
#ifdef USE_GPU
	SAFE_DELETE(gpuDataPtrs);
#endif
}
